/**
 * File Name : AndroidFastRenderView.java
 * <p>
 * Author : maidou
 * <p>
 * Create Time : 2012-11-18, 下午10:23:06
 * <p>
 */

package com.ttomato.game.framework.impl;

import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.view.SurfaceHolder;
import android.view.SurfaceView;

/**
 * Add the description for the file here.
 * <p>
 */
public class AndroidFastRenderView extends SurfaceView implements Runnable
{
    AndroidGame mGame;
    
    Bitmap mFrameBuffer;
    
    Thread mRenderThread;
    
    SurfaceHolder mHolder;
    
    volatile boolean mRunning = false;
    
    public AndroidFastRenderView(AndroidGame game, Bitmap framebuffer)
    {
        super(game);
        mGame = game;
        mFrameBuffer = framebuffer;
        mHolder = getHolder();
    }
    
    public void resume()
    {
        mRunning = true;
        mRenderThread = new Thread(this);
        mRenderThread.start();
    }
    
    public void pause()
    {
        mRunning = false;
        
        while (true)
        {
            try
            {
                mRenderThread.join();
                break;
            }
            catch (Exception e)
            {
                e.printStackTrace();
            }
        }
    }
    
    @Override
    public void run()
    {
        Rect dstRect = new Rect();
        long startTime = System.nanoTime();
        
        while (mRunning)
        {
            if (!mHolder.getSurface().isValid())
            {
                continue;
            }
            
            float deltaTime = (System.nanoTime() - startTime) / 1000000000.0f;
            startTime = System.nanoTime();
            mGame.getCurrentScreen().update(deltaTime);
            mGame.getCurrentScreen().present(deltaTime);
            
            Canvas canvas = mHolder.lockCanvas();
            canvas.getClipBounds(dstRect);
            canvas.drawBitmap(mFrameBuffer, null, dstRect, null);
            mHolder.unlockCanvasAndPost(canvas);
        }
    }
}
